//
//  HMHomeTableViewController.swift
//  WeiBoSwift
//
//  Created by hgj on 2016/11/16.
//  Copyright © 2016年 HuGuoJian. All rights reserved.
//

import UIKit

private let status_id = "status_cell"
private let retweete_id = "retweetedstatus_cell"

let originalCell = UINib(nibName: "HMStatuesCell", bundle: nil).instantiate(withOwner: nil, options: nil).last as! HMStatuesCell
let retweetedCell = UINib(nibName: "HMRetweetedStatusCell", bundle: nil).instantiate(withOwner: nil, options: nil).last as! HMStatuesCell

class HMHomeTableViewController: HMBaseTableViewController {

    // ??
    lazy var needLoadArrray: [IndexPath] = [IndexPath]()
    
    // 实例化对象
    lazy var homeVM: HMHomeViewModel = HMHomeViewModel()
    
     lazy var hmRefreshControl: HMRefreshControl = HMRefreshControl()
    
    var count = 0 //
    
    //实例化提示加载数据的UILabel控件
    private lazy var tipLabel: UILabel = {
        let l = UILabel(title: "", titleColor: UIColor.white, fontSize: 16)
        //设置背景颜色
        l.backgroundColor = UIColor.orange
        //设置隐藏
        l.textAlignment = .center
        l.isHidden = true
        return l
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

       if !userLogin {
            visitorView.updateInfo(title: "关注一些人,回到这里看看有什么惊喜", imageName: "visitordiscover_feed_image_smallicon",isHome: true)
            return
        }
        
        // 自定义按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem( imageName: "navigationbar_pop", target: self, action: #selector(clickSacn))
//        navItem.rightBarButtonItem = UIBarButtonItem( imageName: "navigationbar_pop", target: self, action: #selector(clickSacn))
        
        // 设置 tableView
        setupTableView()
        
        loadData()
    }
    
    func loadData() {
        
        homeVM.loadData(isPullup: indicatorView.isAnimating) { (isSuccess,count) in
            if !isSuccess {
                print("数据加载失败")
                return
            }
            
            
            // 这个判断处理一个细节: 上拉的时候不执行顶部提示动画
            if !self.indicatorView.isAnimating{
                self.startAnimtaion(count: count)
            }

            //需要停止菊花转动 否则只能加载两次数据 (初次+ 第二次)
            self.indicatorView.stopAnimating()
            //停止转动
//            self.refreshControl?.endRefreshing()
            self.hmRefreshControl.endRefreshing()
            
//            self.startAnimtaion(count: count)
            
            // 加载完数据刷新下tableView
            self.tableView.reloadData()
        }

    }
    
    //提示显示多少条数据
    private func startAnimtaion(count: Int) {
        //如果正在做动画就直接返回
        if tipLabel.isHidden == false {
            return
        }
        let tipText = count == 0 ? "没有新微博" : "有\(count)条微博"
        //设置文字
        tipLabel.text = tipText
        //1. 在开始动画前显示tipLabel
        self.tipLabel.isHidden = false
        
        //在开始动画之前记录Y值
        let y = self.tipLabel.frame.origin.y
        UIView.animate(withDuration: 1, animations: {
            //2. 做动画 修改Y值
            self.tipLabel.frame.origin.y = navBarHeight
        }, completion:{ (_) -> () in
            //3. 回去的动画  延迟
            UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
                self.tipLabel.frame.origin.y = y
            }, completion: { (_) -> () in
                self.tipLabel.isHidden = true
            })
        })
    }

    

    @objc private func clickSacn() {
        navigationController?.pushViewController(HMScanViewController(), animated: true)
    }
    

    private func setupTableView() {
        
        tableView.register(UINib(nibName: "HMStatuesCell", bundle: nil), forCellReuseIdentifier: status_id)
        tableView.register(UINib(nibName: "HMRetweetedStatusCell", bundle: nil), forCellReuseIdentifier: retweete_id)
        
//        tableView.rowHeight = 350
//        tableView.estimatedRowHeight = 350
//        tableView.rowHeight = UITableViewAutomaticDimension
        
        // 设置分割线样式
        tableView.separatorStyle = .none
        
        // 尾部小菊花
        tableView.tableFooterView = indicatorView
        
        
        
        //直接给refreshControl实例化就可以用
//        refreshControl = UIRefreshControl()
        //监听事件类型
//        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
        
        //监听事件
        hmRefreshControl.addTarget(self, action: #selector(loadData), for: .valueChanged)
        self.view.addSubview(hmRefreshControl)
        
        //添加tipLabel
        tipLabel.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 35)
        //self.view.addSubview(tipLabel)
        //添加导航视图控制器的根视图上
        //设置Y值
        tipLabel.frame.origin.y = navBarHeight - 35
        //self.navigationController?.view.addSubview(tipLabel)
        //移动到导航条下面
        self.navigationController?.view.insertSubview(tipLabel, belowSubview: self.navigationController!.navigationBar)

    }
    
    //懒加载 小菊花
    lazy var indicatorView: UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        return indicator
    }()
}

// 代理方法 和 数据源方法
extension HMHomeTableViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeVM.viewModelArray.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let viewModel = homeVM.viewModelArray[indexPath.row]
        
        let cell_id = (viewModel.statues?.retweeted_status == nil ? status_id : retweete_id)
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cell_id, for: indexPath) as! HMStatuesCell
        
        // 判断按需加载的数组
        if needLoadArrray.count > 0 {
            let result = needLoadArrray.contains(where: { (index) -> Bool in
                return index.row == indexPath.row && index.section == indexPath.section
            })
            if !result {
                return cell
            }
        }
        

        cell.viewModel = viewModel
        
        return cell
    }
    
    /*
    // pointee: 数据??
    override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        guard let ip = tableView.indexPathForRow(at: CGPoint(x: 0, y: targetContentOffset.pointee.y)) else {
            return
        }
        guard let cip = tableView.indexPathsForVisibleRows?.first else {
            return
        }
        let skipCount = 12
        
        if labs(cip.row - ip.row) > skipCount {
            guard let temp = tableView.indexPathsForRows(in: CGRect(x: 0, y: targetContentOffset.pointee.y, width: view.frame.width, height: view.frame.height)) else {
                return
            }
            
            var arr = temp
            
            if velocity.y < 0 {
                <#code#>
            }
        }
        needLoadArrray.append(contentsOf: arr)
    }
    */
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        if indicatorView.isAnimating == false && indexPath.row == homeVM.viewModelArray.count - 2 {
            
            indicatorView.startAnimating()
            
            loadData()
        }
    }
    
    
     //先调用获取行高的协议方法
     override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
     //获取cell
     let viewModel = self.homeVM.viewModelArray[indexPath.row]
     //let cellId = getCellId(viewmodel: viewmodel)
     //从缓存池中获取一个cell
     //由于tableView要显示先调用获取行高的方法  -> 在行高的方法内部会获取缓存的cell  -> dequeueReusableCell: indexPath内部会调用 -> heightForRowAt: ==>新城递归
     //获取cell的时候就不能够使用 dequeueReusableCell: indexPath
     //使用NSBundle的方式加载cell文件']\
     let name = nibName(viewmodel: viewModel)
     let cell = UINib(nibName: name, bundle: nil).instantiate(withOwner: nil, options: nil).last as! HMStatuesCell
     //let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! HMStatusCellpri
     //绑定数据
     
     cell.viewModel = viewModel
     //cell是自动布局, 设置了数据自动布局并没有立即生效
     cell.layoutIfNeeded()
     //        print(cell.toolBar.frame.maxY)
     
     return cell.toolBar.frame.maxY
     }
     
     
     private func nibName(viewmodel: HMStatusesViewModel) -> String {
     return (viewmodel.statues?.retweeted_status == nil) ? "HMStatuesCell" : "HMRetweetedStatusCell"
     }
     /// 根据数据获取可重用标识符
     ///
     /// - Parameter viewmodel: 视图模型
     /// - Returns: 标识符
    
}

